<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>全局参数配置</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="config-tabs">
        <!-- 邮件通知配置 -->
        <el-tab-pane label="邮件通知" name="email">
          <el-form ref="emailFormRef" :model="emailFormData" :rules="emailFormRules" label-width="140px" class="email-config-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮件标头" prop="emailName">
                  <el-input v-model="emailFormData.emailName" placeholder="请输入邮件标头" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否启用" prop="isActive">
                  <el-switch v-model="emailFormData.isActive" active-text="启用" inactive-text="禁用" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮件服务器主机" prop="emailHost">
                  <el-input v-model="emailFormData.emailHost" placeholder="例如：smtp.qq.com" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮件服务器端口" prop="emailPort">
                  <el-input-number v-model="emailFormData.emailPort" placeholder="例如：587" :min="1" :max="65535" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="使用安全连接" prop="emailSecure">
                  <el-switch v-model="emailFormData.emailSecure" active-text="是" inactive-text="否" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮件服务器用户名" prop="emailUser">
                  <el-input v-model="emailFormData.emailUser" placeholder="例如：user@example.com" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮件服务器密码" prop="emailPassword">
                  <el-input v-model="emailFormData.emailPassword" type="password" placeholder="请输入邮件服务器密码" show-password clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收件人邮箱地址" prop="emailToAddress">
                  <el-input v-model="emailFormData.emailToAddress" placeholder="例如：admin@example.com" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="handleSaveEmailConfig" :loading="emailLoading">
                {{ isEditMode ? "更新配置" : "保存配置" }}
              </el-button>
              <el-button @click="handleResetEmailForm">重置</el-button>
              <el-button type="success" @click="handleTestEmail" :loading="testEmailLoading"> 测试邮件发送 </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 其他配置可以在这里添加 -->
        <el-tab-pane label="其他配置" name="other">
          <div class="empty-content">
            <el-empty description="其他配置功能开发中..." />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { updateEmailConfig, getEmailConfig, createEmailConfig, testSendEmail } from "@/api/common";

// 响应式数据
const activeTab = ref("email");
const emailFormRef = ref<FormInstance>();
const emailLoading = ref(false);
const testEmailLoading = ref(false);
const isEditMode = ref(false);
const currentConfigId = ref("");

// 邮件配置表单数据
const emailFormData = reactive({
  emailName: "",
  emailHost: "",
  emailPort: 587,
  emailSecure: false,
  emailUser: "",
  emailPassword: "",
  emailToAddress: "",
  emailToName: "",
  isActive: true
});

// 表单验证规则
const emailFormRules: FormRules = {
  emailHost: [{ required: true, message: "请输入邮件服务器主机地址", trigger: "blur" }],
  emailPort: [
    { required: true, message: "请输入邮件服务器端口", trigger: "blur" },
    { type: "number", min: 1, max: 65535, message: "端口号必须在1-65535之间", trigger: "blur" }
  ],
  emailUser: [
    { required: true, message: "请输入邮件服务器用户名", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  emailPassword: [{ required: true, message: "请输入邮件服务器密码", trigger: "blur" }],
  emailToAddress: [
    { required: true, message: "请输入收件人邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ]
};

/**
 * 获取邮件配置数据
 * 从接口获取已配置的邮件信息
 */
const fetchEmailConfig = async () => {
  try {
    const res = await getEmailConfig();
    console.log("获取邮件配置:", res);

    if (res.data && res.data.length > 0) {
      // 获取第一个配置（或者可以根据isActive筛选）
      const config = res.data.find((item: any) => item.isActive) || res.data[0];

      if (config) {
        isEditMode.value = true;
        currentConfigId.value = config._id;

        // 填充表单数据
        Object.assign(emailFormData, {
          emailName: config.emailName || "",
          emailHost: config.emailHost || "",
          emailPort: config.emailPort || 587,
          emailSecure: config.emailSecure || false,
          emailUser: config.emailUser || "",
          emailPassword: config.emailPassword || "",
          emailToAddress: config.emailToAddress || "",
          emailToName: config.emailToName || "",
          isActive: config.isActive !== undefined ? config.isActive : true
        });
      }
    } else {
      // 无数据，新增模式
      isEditMode.value = false;
      currentConfigId.value = "";
    }
  } catch (error) {
    console.error("获取邮件配置失败:", error);
    ElMessage.error("获取邮件配置失败");
  }
};

/**
 * 保存邮件配置
 * 根据是否有配置ID判断调用新增或更新接口
 */
const handleSaveEmailConfig = async () => {
  if (!emailFormRef.value) return;

  try {
    await emailFormRef.value.validate();
    emailLoading.value = true;

    if (isEditMode.value && currentConfigId.value) {
      // 更新邮件配置
      await updateEmailConfig(currentConfigId.value, emailFormData);
      ElMessage.success("邮件配置更新成功");
    } else {
      // 创建邮件配置
      const res = await createEmailConfig(emailFormData);
      if (res.data && res.data._id) {
        currentConfigId.value = res.data._id;
        isEditMode.value = true;
      }
      ElMessage.success("邮件配置保存成功");
    }
  } catch (error) {
    console.error("保存邮件配置失败:", error);
    ElMessage.error("保存邮件配置失败");
  } finally {
    emailLoading.value = false;
  }
};

/**
 * 重置邮件表单
 * 清空所有表单字段
 */
const handleResetEmailForm = () => {
  if (!emailFormRef.value) return;

  emailFormRef.value.resetFields();

  // 重置为默认值
  Object.assign(emailFormData, {
    emailName: "",
    emailHost: "",
    emailPort: 587,
    emailSecure: false,
    emailUser: "",
    emailPassword: "",
    emailToAddress: "",
    emailToName: "",
    isActive: true
  });
};

/**
 * 测试邮件发送功能
 * 发送测试邮件验证配置是否正确
 */
const handleTestEmail = async () => {
  if (!emailFormRef.value) return;

  try {
    await emailFormRef.value.validate();

    await ElMessageBox.confirm(`将向 ${emailFormData.emailToAddress} 发送测试邮件，确认继续？`, "测试邮件发送", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info"
    });

    testEmailLoading.value = true;
    // 模拟测试邮件发送
    await testSendEmail();
    ElMessage.success("测试邮件发送成功，请检查收件箱");
  } catch (error) {
    if (error !== "cancel") {
      console.error("测试邮件发送失败:", error);
      ElMessage.error("测试邮件发送失败");
    }
  } finally {
    testEmailLoading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  fetchEmailConfig();
});
</script>

<style scoped lang="less">
.app-container {
  padding: 20px;
}

.box-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    font-size: 16px;
  }
}

.config-tabs {
  margin-top: 20px;

  .email-config-form {
    max-width: 1000px;

    .el-form-item {
      margin-bottom: 20px;
    }
  }

  .empty-content {
    text-align: center;
    padding: 60px 0;
  }
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
